﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Globalization;
using SSPharma.Utility;
using System.Windows.Controls.Primitives;
using System.Reflection;
using System.Collections;
using SSPharma.Utility.Filter;
using System.Collections.ObjectModel;

namespace SSPharma.View
{
    /// <summary>
    /// Interaction logic for frmDangKyNguoiDung.xaml
    /// </summary>
    public partial class frmDangKyNguoiDung : UserControl
    {
        #region Constant

        private const string All = "All";
        private const string MULTI_VAL = "MultiValue";
        private const string CUSTOM = "Custom";


        #endregion

        #region Variables

        private bool isStayOpen = false;

        #endregion

        #region Constructors

        public frmDangKyNguoiDung()
        {
            InitializeComponent();
        }

        #endregion

        #region event handlers

        private void AutoFilterMouseDown(object sender, MouseButtonEventArgs e)
        {

            e.Handled = true;

            if (e.ChangedButton == MouseButton.Right)
                return;
            var columnHeader = FindControls.FindParent<DataGridColumnHeader>((ContentControl)sender);

            var popup = FindControls.FindChild<Popup>(columnHeader, "popFilter");

            if (popup == null) return;
            isStayOpen = true;
            popup.IsOpen = true;

            var listbox = FindControls.FindChild<ListBox>(popup.Child, "autoFilterList");
            listbox.Focus();


        }

        private void DataGrid_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (isStayOpen)
            {
                e.Handled = true;
                isStayOpen = false;
            }
        }

        private void AutoFilterRightMouseDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            var Panel = FindControls.FindParent<StackPanel>((CheckBox)sender);

            var listbox = FindControls.FindChild<ListBox>(Panel, "autoFilterList");
            foreach (var item in listbox.Items)
            {
                CheckedListItem<string> unboxItem = item as CheckedListItem<string>;
                unboxItem.IsChecked = (sender as CheckBox).IsChecked == true ? true : false;
            }
        }


        #endregion

        #region Private methods

        private void popFilter_GotFocus(object sender, RoutedEventArgs e)
        {
            UpdateData(sender as Popup);
        }

        private void UpdateData(Popup popup)
        {
            DataGridColumnHeader columnHeader = FindControls.FindParent<DataGridColumnHeader>(popup);
            DataGridColumn column = columnHeader != null ? columnHeader.Column : null;
            if (columnHeader == null || column == null)
            {
                return;
            }

            DataGrid dataGrid = FindControls.FindParent<DataGrid>(columnHeader);
            if (dataGrid == null)
            {
                return;
            }
            if (column.DisplayIndex >= dataGrid.Columns.Count)
            {
                return;
            }

            //Get datasource
            PropertyInfo datasourcProInfo = DataContext.GetType().GetProperty("DataSource");
            IEnumerable datasource = (IEnumerable)datasourcProInfo.GetValue(DataContext, null);

            //Ger Property info of property that map with current column
            PropertyInfo colPropInfo = datasource.GetType().GetGenericArguments()[0].GetProperty(columnHeader.Content.ToString());

            //Get filter datasource
            PropertyInfo filterDatasourcProInfo = DataContext.GetType().GetProperty("MapColNameToFilter");
            Dictionary<string, Dictionary<string, FilterBase>> filterDatasource =
                (Dictionary<string, Dictionary<string, FilterBase>>)filterDatasourcProInfo.GetValue(DataContext, null);

            //Init dictionary of filters
            Dictionary<string, FilterBase> dicFilters;
            if (!filterDatasource.TryGetValue(columnHeader.Content.ToString(), out dicFilters))
            {
                dicFilters = new Dictionary<string, FilterBase>();
                filterDatasource[columnHeader.Content.ToString()] = dicFilters;

                //*Customer filter
                FilterBase customFilter = FilterBase.CreateCustomFilter(colPropInfo);
                dicFilters[CUSTOM] = customFilter;

                var grid = FindControls.FindChild<Grid>(popup, "customFilterUI");
                if (customFilter == null)
                {
                    grid.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    grid.DataContext = customFilter;
                }

            }

            /* Multi value filter */
            //Initialize item list
            FilterBase multiValFilter;
            if (dicFilters.TryGetValue(MULTI_VAL, out multiValFilter))
            {
                multiValFilter = new MultiValueFilter(colPropInfo);
                dicFilters[MULTI_VAL] = multiValFilter;

                var listbox = FindControls.FindChild<ListBox>(popup, "autoFilterList");
                listbox.ItemsSource = (multiValFilter as MultiValueFilter).FilterList;
            }

            foreach (object element in datasource)
            {
                try
                {
                    object value = colPropInfo.GetValue(element, null);
                    if (!CheckItemExist((multiValFilter as MultiValueFilter).FilterList, value.ToString()))
                    {
                        (multiValFilter as MultiValueFilter).FilterList.Add(new CheckedListItem<string>(value.ToString(), dataGrid.ItemsSource as ListCollectionView, true));
                    }
                }
                catch
                { }
            }





        }

        private bool CheckItemExist(ObservableCollection<CheckedListItem<string>> listFilterItems, string value)
        {
            foreach (var item in listFilterItems)
            {
                if (item.Item.Equals(value))
                {
                    return true;
                }
            }
            return false;
        }

        #endregion
    }

    public class EnumMatchToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType,
                              object parameter, CultureInfo culture)
        {
            if (value == null || parameter == null)
                return false;

            string checkValue = value.ToString();
            string targetValue = parameter.ToString();
            return checkValue.Equals(targetValue,
                     StringComparison.InvariantCultureIgnoreCase);
        }

        public object ConvertBack(object value, Type targetType,
                                  object parameter, CultureInfo culture)
        {
            if (value == null || parameter == null)
                return null;

            bool useValue = (bool)value;
            string targetValue = parameter.ToString();
            if (useValue)
                return Enum.Parse(targetType, targetValue);

            return null;
        }
    }   
}
